<template>
  <div>
    <div :id="code" />
    <a-modal title="查看运行轨迹" :visible="visible" width="604px" :footer="null" @cancel="handleCancel" destroyOnClose>
       <div style="width: 100%;height: 400px" id="allmap"></div>
    </a-modal>
  </div>
</template>

<script>
/* eslint-disable */
import {request} from "../../utils/request";
import checkPermission from "../../utils/permission";
import axios from "axios";
import {environmentMonitoringService} from "../../services";
import carIcon from '@/assets/img/car.png'
import startIcon from '@/assets/img/startIcon.png'
import endIcon from '@/assets/img/endIcon.png'

export default {
  name: "list",
  data() {
    return {
      baseURL: process.env.VUE_APP_SUYUAN_URL,
      amisScoped: null,
      object: {},
      visible: false,
    };
  },
  computed: {
    code() {
      return this.$route.meta.amis;
    },
    userInfo() {
      return this.$store.getters["account/user"];
    },
  },
  watch: {
    code() {
      this.init();
    },
  },
  // 添加created,注册window全局函数
  created() {
    window.viewTrack = (id) => {
      this.queryDetail(id)
      this.visible = true

    };
  },
  methods: {
    init() {
      if (this.amisScoped) {
        this.amisScoped.unmount();
      }
      this.$nextTick(() => {
        // "@/assets/json/" + this.code + ".json"
        if(!this.code){
          return false
        }
        let path = `${process.env.BASE_URL}json/${this.code}.json`
        axios.get(path).then(res=>{
          let amisJSON = res.data
          // this.permission(amisJSON);
          this.amisScoped = this.$amis.embed(
              "#" + this.code,
              amisJSON,
              {
                data: {
                  myData: 1,
                      addBtn: "新增",
                      detailBtn: "查看",
                      deleteBtn: "删除",
                      editBtn: "编辑",
                      enableBtn: "启用/禁用",
                      exportBtn: "导出",
                      loginUserId:this.userInfo.loginUserId
                },
              },
              {
                // 可以不传，用来实现 ajax 请求
                fetcher: ({ url, method, data, config }) => {
                  console.log(url, method,)
                  if (!data) {
                    data = {};
                  }
                  data["tenantCode"] = sessionStorage.getItem("tenantCode");
                  data["subjectInfoId"] = sessionStorage.getItem("subjectInfoId");
                  data["subjectEnterpriseType"] = sessionStorage.getItem("subjectEnterpriseType");
                  data["milkStationFlag"] = sessionStorage.getItem("milkStationFlag");
                  data["traceabilityAddressUrl"] = process.env.TRACEABILITY_ADDRESS_URL;
                  console.log("traceabilityAddressUrl",process.env.TRACEABILITY_ADDRESS_URL)
                  data["loginUserId"] = this.userInfo.loginUserId;
                  return request(url, method, data, config);
                },
                theme: "antd",
              }
          );
          // this.amisScoped.updateProps({
          //   data: {
          //     addBtn: "新增",
          //     detailBtn: "查看",
          //     deleteBtn: "删除",
          //     editBtn: "编辑",
          //     enableBtn: "启用/禁用",
          //   },
          // });
        })
      });
    },
    permission(data) {
      for (let key in data) {
        if (typeof data[key] === "object") {
          if (Array.isArray(data[key])) {
            for (let i = 0; i < data[key].length; i++) {
              this.permission(data[key][i]);
            }
          } else {
            this.permission(data[key]);
          }
        } else {
          if (data["permission"]) {
            data["className"] = !checkPermission(this.code, data["permission"])
              ? "no-permission"
              : "";
          }
        }
      }
    },
    queryDetail(id){
      environmentMonitoringService.freshMilkDelivery(id).then(res=>{
        this.object = res.data.data
        this.$nextTick(()=>{
          this.setMap()
        })
      })
    },
    handleCancel(){
      this.visible = false
    },
    setMap(){
      var pts = [];
      this.object.vehicleDeviceCollectionInfos.forEach(
        item=> {
          if(item.postionFlag == 0){
            pts.push(new BMap.Point(item.longitudeBaidu, item.latitudeBaidu))
          }
      })  //通过驾车实例，获得一系列点的数组
      console.log("pts-----",pts)
      var paths = pts.length;    //获得有几个点
      var map = new BMap.Map("allmap");
      map.enableScrollWheelZoom();
      map.centerAndZoom(pts[0], 16);
      var myP1 = pts[0];    //起点
      var myP2 = pts[paths-1];    //终点
      var myIcon = new BMap.Icon(carIcon, new BMap.Size(40, 21), {    //小车图片
        //offset: new BMap.Size(0, -5),    //相当于CSS精灵
        imageSize: new BMap.Size(40, 21),
        imageOffset: new BMap.Size(0, 0)    //图片的偏移量。为了是图片底部中心对准坐标点。
      });
      var lushu;
      var drv = new BMap.DrivingRoute(myP1, {
        onSearchComplete: function(res) {
          if (drv.getStatus() == BMAP_STATUS_SUCCESS) {
            var plan = res.getPlan(0);
            var arrPois =[];
            for(var j=0;j<plan.getNumRoutes();j++){
              var route = plan.getRoute(j);
              arrPois= arrPois.concat(route.getPath());
            }
            map.addOverlay(new BMap.Polyline(arrPois, {strokeColor: '#61A4FF'}));
            map.setViewport(arrPois);
            lushu = new BMapLib.LuShu(map,arrPois, {
              autoView:true,//是否开启自动视野调整，如果开启那么路书在运动过程中会根据视野自动调整
              icon  : myIcon,
              speed: 30000,
              enableRotation:true,//是否设置marker随着道路的走向进行旋转
            });
            lushu.start();
          }
        }
      });
      var marker = new BMap.Marker(myP1, {
        icon: new BMap.Icon(startIcon, new BMap.Size(30, 30), {    //小车图片
          //offset: new BMap.Size(0, -5),    //相当于CSS精灵
          imageSize: new BMap.Size(30, 30),
          imageOffset: new BMap.Size(0, 0)    //图片的偏移量。为了是图片底部中心对准坐标点。
        })
      });
      var marker2 = new BMap.Marker(myP2, {
        icon: new BMap.Icon(endIcon, new BMap.Size(30, 30), {    //小车图片
          //offset: new BMap.Size(0, -5),    //相当于CSS精灵
          imageSize: new BMap.Size(30, 30),
          imageOffset: new BMap.Size(0, 0)    //图片的偏移量。为了是图片底部中心对准坐标点。
        })
      });  // 创建标注
      // 创建标注
      map.addOverlay(marker);
      map.addOverlay(marker2);
      // 将标注添加到地图中
      drv.search(myP1, myP2);

    }
  },
  mounted() {
    this.init();
  },
  destroyed() {
    console.log("==================");
    this.amisScoped.unmount();
  },
};
</script>
